using System.Collections;
using MyFramework.Mono;
using MyFramework.Singleton;
using UnityEngine;
using UnityEngine.Events;

namespace MyFramework.Resource
{
    /// <summary>
    /// 资源加载模块
    /// 1.异步加载
    /// 2.委托和lambda表达式
    /// 3.协程
    /// 4.泛型
    /// </summary>
    public class ResourcesManager : Singleton<ResourcesManager>
    {
        public T Load<T>(string name) where T : Object
        {
            var resource = Resources.Load<T>(name);

            //如果资源是GameObject类型，直接实例化再返回；如果不是就直接返回
            return resource is GameObject ? Object.Instantiate(resource) : resource;
        }
        
        public void LoadAsync<T>(string name, UnityAction<T> callback) where T : Object
        {
            //使用公共Mono模块开启异步加载的协程
            MonoManager.GetInstance().StartCoroutine(ReallyLoadAsync(name, callback));
        }
        
        private static IEnumerator ReallyLoadAsync<T>(string name, UnityAction<T> callback) where T : Object
        {
            ResourceRequest resourceRequest = Resources.LoadAsync<T>(name);
            yield return resourceRequest;

            //如果资源是GameObject类型，实例化再回调；如果不是就回调
            if (resourceRequest.asset is GameObject)
                callback(Object.Instantiate(resourceRequest.asset) as T);
            else
                callback(resourceRequest.asset as T); 
        }
    }
}
